package DAO;

import java.util.ArrayList;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import Beans.Branch;
import Beans.Terminal;
import Utils.HibernateUtil;

public class TerminalDao {

	private SessionFactory sessionFactory;
	private Transaction tr = null;

	public TerminalDao() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}
	
	/**
	 * 删除终端
	 */
	public void delete(Terminal terminal) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.delete(terminal);
		tr.commit();
		session.close();
	}
	
	/**
	 * 修改终端
	 */
	public void edit(Terminal terminal) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.update(terminal);
		tr.commit();
		session.close();
	}
	
	/**
	 * 返回所有终端
	 * @return
	 */
	public ArrayList<Terminal> returnAllTermials() {

		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		
			ArrayList<Terminal> terminals = null;
	
			Criteria c = session.createCriteria(Terminal.class);
			c.add(Restrictions.eq("status", 0));
			c.addOrder(Order.asc("terminalId"));
			terminals = (ArrayList<Terminal>) c.list();
	
		tr.commit();
		
		
		session.close();
		return terminals;
	}
	/**
	 * 查询网点内的所有终端
	 * @param branchID 网点号
	 * @return
	 */
	public ArrayList<Terminal> returnTermialByBranchID(int branchId) {

		BranchDao branchDao=new BranchDao();
		Branch branch=branchDao.getBranchById(branchId);
		Session session = sessionFactory.openSession();
			tr = session.beginTransaction();
		
			ArrayList<Terminal> terminals = null;
	
			Criteria c = session.createCriteria(Terminal.class);
			c.add(Restrictions.eq("branch",branch));
			c.add(Restrictions.eq("status",0));
			terminals = (ArrayList<Terminal>) c.list();
	
			tr.commit();
		session.close();
		return terminals;
	}
	
	/**
	 * 通过终端号返回指定终端
	 * @param terminalId
	 * @return
	 */
	public Terminal getTerminalById(int terminalId){
		
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Terminal terminal=(Terminal) session.get(Terminal.class, terminalId);
		tr.commit();
		session.close();
		return terminal;
		
	}
	/**
	 *新增终端 
	 */
	public void save(Terminal terminal){
		Session session=sessionFactory.openSession();
		
		tr=session.beginTransaction();
		session.save(terminal);
		tr.commit();
		session.close();
		
	}
	
}
